<template>
  <div v-loading="loading" class="dataForm">
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="120px"
    >
      <el-row v-if="form.lastHistoricalId" :span="24">
        <div style="float: right;">
          <el-button size="mini" type="primary" style=" margin-right: 50px;" @click="contractComparisonBtn">
            {{ $t('合同比对') }}
          </el-button>
        </div>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('申请标题')" prop="actTitle">
            <el-input v-model="form.actTitle" :placeholder="$t('申请标题')" show-word-limit :maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请人')" prop="applyUserId">
            <UserSelect
              v-model="form.applyUserId"
              :placeholder="$t('申请人')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('申请时间')" prop="applyTime">
            <DatePicker v-model="form.applyTime" :placeholder="$t('申请时间')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('合同名称')" prop="name">
            <el-input v-model="form.name" :placeholder="$t('合同名称')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="type">
            <span slot="label">
              {{ $t('合同类型') }}
              <el-tooltip :content="$t('类型为“投资协议”并且为“付款”时,审批完成后将会把当前合同中的签约主体同步至项目主体中')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <el-select v-model="form.type" value="" :placeholder="$t('请选择')" filterable clearable @change="changeIsPayment()">
              <el-option
                v-for="dict in getTypeDict"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('收付款类型')" prop="isPayment">
            <el-radio-group v-model="form.isPayment">
              <el-radio
                v-for="dict in isPaymentOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{ $t(dict.dictLabel) }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('是否用印')" prop="isSeal">
            <el-radio-group v-model="form.isSeal">
              <el-radio
                v-for="dict in isSealOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{ $t(dict.dictLabel) }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <!--
        <el-col :span="12">
          <el-form-item :label="交易对手" prop="company">
            <el-input v-model="form.company" placeholder="请输入交易对手" maxlength="50" />
          </el-form-item>
        </el-col>
        -->
        <el-col v-if="isShowDeal === 'hidden'" :span="12">
          <el-form-item :label="$t('关联项目')" prop="dealId">
            <MainBodySelect
              v-model="form.dealId"
              :show-label="false"
              :parameters="'deal'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-if="form.isPayment === 'collection' || form.isPayment === 'payment'" :label="$t('合同金额') + $t('金额单位')" prop="money">
            <Money v-model="form.money" unit="w" :placeholder="$t('合同金额')" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('合同摘要')" prop="abstracts">
            <el-input v-model="form.abstracts" type="textarea" maxlength="2000" :placeholder="$t('合同摘要')" />
          </el-form-item>
        </el-col>
        <el-col v-if="form.isPayment === 'payment'" :span="24">
          <el-form-item :label="$t('付款先决条件')" prop="paymentPrerequisites">
            <el-input v-model="form.paymentPrerequisites" type="textarea" maxlength="2000" :placeholder="$t('付款先决条件')" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('特殊条款')" prop="specialTerms">
            <el-input v-model="form.specialTerms" type="textarea" maxlength="2000" :placeholder="$t('特殊条款')" />
          </el-form-item>
        </el-col>
      </el-row>

      <!--用印明细-->
      <div v-if="form.isSeal === 'Y'" style="margin-top:8px;">
        <div class="area-header">
          <span class="area-header-title">{{ $t('用印明细') }}</span>
        </div>
        <el-table tooltip-effect="darkTable" :data="form.oaSealDetailList" border class="nowrapTable formTable">
          <el-table-column :label="$t('序号')" align="center" width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('用印主体类型')" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('用印主体类型') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'oaSealDetailList.' + scope.$index + '.investMainType'" :rules="oaSealDetailListRules.investMainType">
                <dictSelect
                  v-model="scope.row.investMainType"
                  :clearable="true"
                  dictionary="main_body_type"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('用印主体')" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('用印主体') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'oaSealDetailList.' + scope.$index + '.investMain'" :rules="oaSealDetailListRules.investMain">
                <MainBodySelect
                  v-model="scope.row.investMain"
                  :parameters="scope.row.investMainType"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('用印类型')">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('用印类型') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'oaSealDetailList.' + scope.$index + '.sealType'" :rules="oaSealDetailListRules.sealType">
                <el-select
                  v-model="scope.row.sealType"
                  multiple
                  filterable
                  :placeholder="$t('用印类型')"
                >
                  <el-option
                    v-for="dict in sealTypeDict"
                    :key="dict.dictValue"
                    :label="$t(dict.dictLabel)"
                    :value="dict.dictValue"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('备注')" align="center">
            <template slot-scope="scope">
              <el-form-item :prop="'oaSealDetailList.' + scope.$index + '.remark'" :rules="oaSealDetailListRules.remark">
                <el-input v-model="scope.row.remark" type="textarea" :placeholder="$t('备注')" maxlength="2000" class="fileTextarea" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column v-if="!otherBtnHide" :label="$t('操作')" align="center" width="60px">
            <template slot-scope="scope">
              <el-button v-hasPermi="['bf:contract:remove']" type="text" icon="el-icon-delete" @click="delHandle(scope.$index, scope.row)" />
            </template>
          </el-table-column>
        </el-table>
        <div class="tol">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="addPayment">{{ $t("添加") }}</el-button>
        </div>
      </div>

      <!--签约主体-->
      <div v-loading="bfContractPaymentLoading">
        <div style="margin-top:15px;">
          <div class="area-header">
            <span class="area-header-title">{{ $t('签约主体') }}</span>
          </div>
          <el-table tooltip-effect="darkTable" :data="form.bfContractPaymentList" border class="nowrapTable formTable">
            <el-table-column :label="$t('序号')" align="center" width="50">
              <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column :label="$t('主体类型')" align="center" min-width="80">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949;margin-right: 4px;">*</i>
                <span>{{ $t('主体类型') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'bfContractPaymentList.' + scope.$index + '.investType'" :rules="bfContractPaymentListRules.investType">
                  <dictSelect
                    v-model="scope.row.investType"
                    :clearable="true"
                    dictionary="deal_investment_type"
                    @change="changeInvestType(scope.$index)"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('主体名称')" align="center" min-width="200">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949;margin-right: 4px;">*</i>
                <span>{{ $t('主体名称') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'bfContractPaymentList.' + scope.$index + '.investMain'" :rules="bfContractPaymentListRules.investMain">
                  <MainBodySelect
                    v-model="scope.row.investMain"
                    :parameters="scope.row.investType"
                    @change="changeInvestData"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <!--
            <el-table-column :label="$t('SPV')" align="center">
              <template slot="header" slot-scope="{}">
                <span>{{ $t('SPV') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'bfContractPaymentList.' + scope.$index + '.spvId'" :rules="bfContractPaymentListRules.spvId">
                  <spv-select v-model="scope.row.spvId" />
                </el-form-item>
              </template>
            </el-table-column>
            -->
            <el-table-column v-if="form.type === 'TZXY'" :label="$t('投资金额') + $t('金额单位')" align="center" min-width="100">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949;margin-right: 4px;">*</i>
                <span>{{ $t('投资金额') + $t('金额单位') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'bfContractPaymentList.' + scope.$index + '.investmentAmount'" :rules="bfContractPaymentListRules.investmentAmount">
                  <Money v-model="scope.row.investmentAmount" unit="w" :placeholder="$t('投资金额')" @change="investmentAmountCompute" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('认缴比例(%)')" align="center" min-width="80">
              <template slot="header" slot-scope="{}">
                <span>{{ $t('认缴比例(%)') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'bfContractPaymentList.' + scope.$index + '.stake'" :rules="bfContractPaymentListRules.stake">
                  <!--                  <el-input v-model="scope.row.stake" oninput="value=value.replace(/[^\d.]/g,'')" :placeholder="$t('认缴比例(%)')" />-->
                  <Ratio v-model="scope.row.stake" :placeholder="$t('认缴比例(%)')" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('备注')" align="center" min-width="150">
              <template slot="header" slot-scope="{}">
                <span>{{ $t('备注') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'bfContractPaymentList.' + scope.$index + '.remark'">
                  <el-input v-model="scope.row.remark" type="textarea" :placeholder="$t('备注')" maxlength="2000" class="fileTextarea" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column v-if="!otherBtnHide" :label="$t('操作')" align="center" width="60px">
              <template slot-scope="scope">
                <el-button v-hasPermi="['bf:contract:remove']" size="small" type="text" icon="el-icon-delete" @click="delHandlePay(scope.$index, scope.row)" />
              </template>
            </el-table-column>
          </el-table>
          <div v-if="!otherBtnHide" class="tol">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="addPaymentPay">{{ $t("添加") }}</el-button>
          </div>
        </div>

        <!-- ********************************** 收付款计划 ************************************ -->
        <div v-if="nameReceiptPayment === '付款' && (form.isPayment === 'payment')" style="margin-top:15px;">
          <div class="area-header">
            <span class="area-header-title">{{ $t(nameReceiptPayment + '计划') }}</span>
          </div>
          <el-table v-loading="bfContractPaymentLoading" tooltip-effect="darkTable" :data="form.bfContractPlanList" border class="nowrapTable formTable">
            <el-table-column :label="$t('序号')" align="center" width="50">
              <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column :label="$t('主体名称')" align="center">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949;margin-right: 4px;">*</i>
                <span>{{ $t('主体名称') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'bfContractPlanList.' + scope.$index + '.investId'" :rules="bfContractPlanListRules.investId">
                  <el-select v-model="scope.row.investId" clearable size="small">
                    <el-option
                      v-for="dict in bfContractPlanInvestMainOptions"
                      :key="dict.dictValue"
                      :label="$t(dict.dictLabel)"
                      :value="dict.dictValue"
                    />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('预计付款时间')" align="center">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949;margin-right: 4px;">*</i>
                <span>{{ $t('预计付款时间') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'bfContractPlanList.' + scope.$index + '.paymentTime'" :rules="bfContractPlanListRules.paymentTime">
                  <DatePicker v-model="scope.row.paymentTime" :placeholder="$t('预计付款时间')" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('预计付款金额') + $t('金额单位')" align="center">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949;margin-right: 4px;">*</i>
                <span>{{ $t('预计付款金额') }}{{ $t('金额单位') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'bfContractPlanList.' + scope.$index + '.paymentMoney'" :rules="bfContractPlanListRules.paymentMoney">
                  <Money v-model="scope.row.paymentMoney" unit="w" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('币种')" align="center">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949;margin-right: 4px;">*</i>
                <span>{{ $t('币种') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'bfContractPlanList.' + scope.$index + '.currency'" :rules="bfContractPlanListRules.currency">
                  <dictSelect
                    v-model="scope.row.currency"
                    :clearable="true"
                    dictionary="currency"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('备注')" align="center">
              <template slot="header" slot-scope="{}">
                <span>{{ $t('备注') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'bfContractPlanList.' + scope.$index + '.remark'">
                  <el-input v-model="scope.row.remark" type="textarea" :placeholder="$t('备注')" maxlength="2000" class="fileTextarea" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column v-if="!otherBtnHide" :label="$t('操作')" align="center" width="60px">
              <template slot-scope="scope">
                <el-button v-hasPermi="['bf:contract:remove']" size="small" type="text" icon="el-icon-delete" @click="delHandlePlan(scope.$index, scope.row)" />
              </template>
            </el-table-column>
          </el-table>
          <div v-if="!otherBtnHide" class="tol">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="addPaymentPlan">{{ $t("添加") }}</el-button>
          </div>
        </div>

        <div v-if="nameReceiptPayment === '收款' && (form.isPayment === 'collection')" style="margin-top:15px;">
          <div class="area-header">
            <span class="area-header-title">{{ nameReceiptPayment + $t('计划') }}</span>
          </div>
          <el-table v-loading="bfContractPaymentLoading" tooltip-effect="darkTable" :data="form.bfContractPlanList" border class="nowrapTable formTable">
            <el-table-column :label="$t('序号')" align="center" width="50">
              <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column :label="$t('主体名称')" align="center">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949;margin-right: 4px;">*</i>
                <span>{{ $t('主体名称') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'bfContractPlanList.' + scope.$index + '.investId'" :rules="bfContractPlanListRules.investId">
                  <el-select v-model="scope.row.investId" filterable clearable size="small">
                    <el-option
                      v-for="dict in bfContractPlanInvestMainOptions"
                      :key="dict.dictValue"
                      :label="$t(dict.dictLabel)"
                      :value="dict.dictValue"
                    />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('预计收款时间')" align="center">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949;margin-right: 4px;">*</i>
                <span>{{ $t('预计收款时间') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'bfContractPlanList.' + scope.$index + '.collectionTime'" :rules="bfContractPlanListRules.collectionTime">
                  <DatePicker v-model="scope.row.collectionTime" :placeholder="$t('预计收款时间')" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('预计收款金额') + $t('金额单位')" align="center">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949;margin-right: 4px;">*</i>
                <span>{{ $t('预计收款金额') }}{{ $t('金额单位') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'bfContractPlanList.' + scope.$index + '.collectionMoney'" :rules="bfContractPlanListRules.collectionMoney">
                  <Money v-model="scope.row.collectionMoney" unit="w" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('币种')" align="center">
              <template slot="header" slot-scope="{}">
                <i style="color: #ff4949;margin-right: 4px;">*</i>
                <span>{{ $t('币种') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'bfContractPlanList.' + scope.$index + '.currency'" :rules="bfContractPlanListRules.currency">
                  <dictSelect
                    v-model="scope.row.currency"
                    :clearable="true"
                    dictionary="currency"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :label="$t('备注')" align="center">
              <template slot="header" slot-scope="{}">
                <span>{{ $t('备注') }}</span>
              </template>
              <template slot-scope="scope">
                <el-form-item :prop="'bfContractPlanList.' + scope.$index + '.remark'">
                  <el-input v-model="scope.row.remark" type="textarea" :placeholder="$t('备注')" maxlength="2000" class="fileTextarea" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column v-if="!otherBtnHide" :label="$t('操作')" align="center" width="60px">
              <template slot-scope="scope">
                <el-button v-hasPermi="['bf:contract:remove']" size="small" type="text" icon="el-icon-delete" @click="delHandlePlan(scope.$index, scope.row)" />
              </template>
            </el-table-column>
          </el-table>
          <div v-if="!otherBtnHide" class="tol">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="addPaymentPlan">{{ $t("添加") }}</el-button>
          </div>
        </div>
      </div>

      <!--合同关键条款-->
      <div style="margin-top:15px;">
        <div class="area-header">
          <span class="area-header-title">{{ $t('合同关键条款') }}</span>
        </div>
        <el-table tooltip-effect="darkTable" :data="form.bfContractTermsList" border class="nowrapTable formTable tree_el_Table">
          <el-table-column :label="$t('序号')" align="center" width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('条款类型')" align="center" width="300">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('条款类型') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'bfContractTermsList.' + scope.$index + '.type'" :rules="bfContractTermsListRules.type">
                <dictSelect
                  v-model="scope.row.type"
                  :clearable="true"
                  dictionary="key_terms_type_bf"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('条款内容')" align="center" min-width="200">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('条款内容') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'bfContractTermsList.' + scope.$index + '.remark'" :rules="bfContractTermsListRules.remark">
                <el-input
                  v-model="scope.row.remark"
                  type="textarea"
                  :autosize="{ minRows: 1, maxRows: 8}"
                  maxlength="2000"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('定时提醒')" align="center" min-width="100">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="remindHandle(scope.$index)">定时提醒</el-button>
            </template>
          </el-table-column>
          <el-table-column v-if="!otherBtnHide" :label="$t('操作')" align="center" width="60px">
            <template slot-scope="scope">
              <el-button v-hasPermi="['bf:contract:remove']" type="text" icon="el-icon-delete" @click="delHandleTerms(scope.$index, scope.row)" />
            </template>
          </el-table-column>
        </el-table>
        <div v-if="!otherBtnHide" class="tol">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="addPaymentTerms">{{ $t("添加") }}</el-button>
        </div>
      </div>

      <!-- 附件列表 -->
      <FileTable :list.sync="form.fileList" has-permi="bf:contract" data-type="bf_contract" :business-id="dealId" :btn-show="!otherBtnHide" />

      <!-- 合同比对页面 -->
      <el-dialog :title="$t(title)" :visible.sync="bfContractProcessOpen" width="99%" top="1%" :destroy-on-close="true" :close-on-click-modal="false" :lock-scroll="false" append-to-body custom-class="dialogForm">
        <bfContractProcess ref="bfContractProcess" />
      </el-dialog>

    </el-form>
    <div v-if="form.actStatus !== 'D'" slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <FormBtn v-if="!changeContractBtnStatus && !otherBtnHide" ref="formBtn" :bus-data="form" :btn-hide="btnHide" has-permi="bf:contract" :menu-key="menuKey" />
      <div v-if="changeContractBtnStatus && !otherBtnHide">
        <el-button @click="cancel()">{{ $t("取消") }}</el-button>
        <el-button
          v-hasPermi="['deal:contract:edit']"
          type="primary"
          @click="submitFormReady('changeContract')"
        >{{ $t("变更并启动流程") }}</el-button>
      </div>
    </div>
    <!-- 定时提醒 -->
    <el-dialog :title="$t('定时提醒')" :visible.sync="remindOpen" width="40%" :destroy-on-close="true" :close-on-click-modal="false" :lock-scroll="false" append-to-body>
      <el-form
        v-if="form.bfContractTermsList !== undefined && form.bfContractTermsList !== null && form.bfContractTermsList.length > 0 && form.bfContractTermsList[termsIndex]"
        ref="remindForm"
        :model="form.bfContractTermsList[termsIndex]"
        :rules="remindRules"
        label-width="120px"
        label-position="top"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item :label="$t('提醒频率')" prop="reminderFrequency">
              <el-radio-group v-model="form.bfContractTermsList[termsIndex].reminderFrequency">
                <el-radio
                  v-for="dict in reminderFrequencyOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{ $t(dict.dictLabel) }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-if="form.bfContractTermsList[termsIndex].reminderFrequency === 'TIMER'" :span="12">
            <el-form-item :label="$t('定时提醒时间')" prop="remindTime">
              <el-date-picker
                v-model="form.bfContractTermsList[termsIndex].remindTime"
                clearable
                style="width: 200px"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                format="yyyy-MM-dd HH:mm"
                :placeholder="$t('定时提醒时间')"
              />
            </el-form-item>
          </el-col>
          <el-col v-else :span="24">
            <el-form-item :label="$t('频率提醒表达式')" prop="cron">
              <Cron v-model="form.bfContractTermsList[termsIndex].cron" :cron-value.sync="form.bfContractTermsList[termsIndex].frequencyCronValue" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('提醒状态')" prop="status">
              <el-switch
                v-model="form.bfContractTermsList[termsIndex].status"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-text="$t('开启')"
                :inactive-text="$t('关闭')"
                :active-value="1"
                :inactive-value="0"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('提醒人')" prop="remindUserId">
              <UserSelect
                v-model="form.bfContractTermsList[termsIndex].remindUserId"
                :multiple="true"
                :placeholder="$t('提醒人')"
                :popper-append-to-body="true"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="remindConfirmHandle">{{ $t('确 定') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
    import { saveBfContract, getBfContract, delBfContractTerms, delBfContractInvest, findInvestMain, changeBfContract } from '@/api/bf/contract/bfContract'
    import { getLpViewByMainBodyId } from '@/api/oa/contract/oaContract'
    import MainBodySelect from '@/components/MainBodySelect'
    import { deleteFileBase } from '@/api/file/filefolder/folder.js'
    import { deleteOaSealDetail } from '@/api/oa/seal/oaSeal'
    import { findDealBaseSelect } from '@/api/base/deal/dealBase'
    import { getDealName } from '@/api/base/deal/dealBase'
    import bfContractProcess from '@/views/bf/contract/bfContractProcess.vue'
    import Cron from '@/components/Cron'
    export default {
        components: {
          MainBodySelect,
          bfContractProcess,
          Cron
        },
        data() {
            const checkBfContractPaymentList = (rule, value, callback) => {
              if (rule.field.indexOf('paymentTime') !== -1) {
                value = this.form.bfContractPaymentList[parseInt(rule.field.replace(/[^0-9]/ig, ''))].paymentTime
              }
              if (rule.field.indexOf('paymentMoney') !== -1) {
                value = this.form.bfContractPaymentList[parseInt(rule.field.replace(/[^0-9]/ig, ''))].paymentMoney
              }
              if (rule.field.indexOf('currency') !== -1) {
                value = this.form.bfContractPaymentList[parseInt(rule.field.replace(/[^0-9]/ig, ''))].currency
              }
              if (rule.field.indexOf('investType') !== -1) {
                value = this.form.bfContractPaymentList[parseInt(rule.field.replace(/[^0-9]/ig, ''))].investType
              }
              if (rule.field.indexOf('investMain') !== -1) {
                value = this.form.bfContractPaymentList[parseInt(rule.field.replace(/[^0-9]/ig, ''))].investMain
              }
              if (rule.field.indexOf('investmentAmount') !== -1) {
                value = this.form.bfContractPaymentList[parseInt(rule.field.replace(/[^0-9]/ig, ''))].investmentAmount
              }
              if (value === undefined || value === '' || value === null) {
                callback(new Error(this.$t('必填信息')))
              } else {
                callback()
              }
            }
          // 最新持股比例 超过百分比校验
          const checkStake = (rule, value, callback) => {
            if (value === null || value === '' || value === undefined) {
              callback()
            } else {
              var num = 0.0
              if (parseFloat(value) !== undefined && !isNaN(parseFloat(value))) {
                num = parseFloat(value)
              }
              if (num > 100) {
                callback(new Error(this.$t('不能超过100%')))
              } else {
                const indexInt = parseInt(rule.field.substring(rule.field.indexOf('.') + 1, rule.field.lastIndexOf('.')))
                this.form.bfContractPaymentList[indexInt].stake = num.toFixed(2)
                callback()
              }
            }
          }
            // 校验合同金额 不能为0 和负数
            const checkMoney = (rule, value, callback) => {
              if (value === undefined || value === '' || value === 0 || value === '0' || value === null) {
                callback(new Error(this.$t('必填信息')))
              } else {
                callback()
              }
            }
            return {
                // 菜单标识
                menuKey: 'bf_contract_TQ',
                loading: false,
                bfContractPaymentLoading: false,
                // 单选
                isSealOptions: [],
                isPaymentOptions: [],
                // 表单参数
                form: {},
                changeContractBtnStatus: false,
                // 项目ID
                dealId: this.$route.query.id,
                // 是否隐藏保存按钮
                btnHide: false,
                // 是否隐藏其它按钮
                otherBtnHide: false,
              // 定时提醒
              remindOpen: false,
              // 点击定时提醒关键条款索引
              termsIndex: undefined,
              reminderFrequencyOptions: [],
                // 表单校验
                rules: {
                  applyUserId: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  applyTime: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  name: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  money: [{ required: true, validator: checkMoney, trigger: ['blur', 'change'] }],
                  type: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  isPayment: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  isSeal: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  signingTime: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  dealId: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  actTitle: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ]
                },
                // 操作按钮默认不展示
                buttonShow: true,
                oaSealDetailListRules: {
                  investMainType: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  investMain: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  sealType: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
                },
                bfContractPaymentListRules: {
                  investType: [{ required: true, validator: checkBfContractPaymentList,	trigger: 'blur' }],
                  investMain: [{ required: true, validator: checkBfContractPaymentList,	trigger: 'blur' }],
                  investmentAmount: [{ required: true, validator: checkBfContractPaymentList,	trigger: 'blur' }],
                  paymentTime: [{ required: true, validator: checkBfContractPaymentList, trigger: 'blur' }],
                  paymentMoney: [{ required: true, validator: checkBfContractPaymentList,	trigger: 'blur' }],
                  collectionTime: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  collectionMoney: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  currency: [{ required: true, validator: checkBfContractPaymentList,	trigger: 'change' }],
                  stake: [{ required: false, validator: checkStake, trigger: 'blur' }]
                },
                bfContractPlanListRules: {
                  investId: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                  paymentTime: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                  paymentMoney: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                  collectionTime: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
                  collectionMoney: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
                },
                bfContractTermsListRules: {
                  name: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  type: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  remark: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
                },
              remindRules: {
                timerReminderTime: { required: true, message: this.$t('必填信息'), trigger: 'blur' },
                cron: { required: true, message: this.$t('必填信息'), trigger: 'blur' },
                reminderFrequency: { required: true, message: this.$t('必填信息'), trigger: 'blur' },
                remindTime: { required: true, message: this.$t('必填信息'), trigger: 'blur' },
                remindUserId: { required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }
              },
                getTypeDict: [],
                uploaderOpen: false,
                dataType: 'bf_contract',
                title: '',
                isShowDeal: undefined,
                dealBaseOptions: [],
                sealTypeDict: undefined,
                // 收款  付款 名称
                nameReceiptPayment: '',
                // 是否展示最新持股比例
                isShowStake: false,
                bfContractPlanInvestMainOptions: [],
                bfContractPlanInvestMainOptionsTemp: [],
                monitorQueryParams: {
                  dealId: this.$route.query.id,
                  money: 0
                },
                // 旧数据
                oldBfContract: undefined,
                bfContractProcessOpen: false
            }
        },
        watch: {
          'form.isPayment': {
            handler(val) {
              if (val === 'collection') {
                this.nameReceiptPayment = '收款'
              } else if (val === 'payment') {
                this.nameReceiptPayment = '付款'
              } else {
                this.nameReceiptPayment = '收付款'
              }
              if (this.form.type === 'TZXY' && val === 'payment') {
                this.isShowStake = true
              } else {
                this.isShowStake = false
              }
            }
          },
          'form.type': {
            handler(val) {
              if (val === 'TZXY' && this.form.isPayment === 'payment') {
                this.isShowStake = true
              } else {
                this.isShowStake = false
              }
            }
          }
        },
        created() {
            this.$bus.$emit('async_done')
            this.getDicts('sys_yes_no').then(response => {
              this.isSealOptions = response.data
            })
          this.getDicts('reminder_frequency').then(response => {
            this.reminderFrequencyOptions = response.data
          })
            this.getDicts('deal_contract_type_select').then(response => {
              this.getTypeDict = response.data
            })

            this.getDicts('payment_no_deal').then(response => {
              this.isPaymentOptions = response.data
            })
            this.getDicts('seal_type').then(response => {
              this.sealTypeDict = response.data
            })
        },
        methods: {
          // 初始化数据
          init(data) {
            this.changeContractBtnStatus = false
            this.initForm(data, () => {})
          },
          // 初始化数据
          initForm(data, callback) {
            this.dealId = this.$route.query.id ? this.$route.query.id : data.dealId
            if (this.dealId === undefined || this.dealId === null || this.dealId === '') {
              this.isShowDeal = 'hidden'
              findDealBaseSelect().then(response => {
                this.dealBaseOptions = response.data
              })
            }
            if (data != null && data.id !== undefined && data.id !== '' && data.id !== null) {
              this.loading = true
              getBfContract(data.id).then(response => {
                this.form = response.data
                this.changeContractBtnStatus = (this.form.actStatus === 'D' || this.form.actStatus === 'W')
                this.form.isPayment = response.data.isPayment
                this.form.isSeal = response.data.isSeal
                this.bfContractPlanInvestMainOptions = []
                this.loadingPlanName()
                // 备份数据
                this.oldBfContract = JSON.parse(JSON.stringify(this.form))
                this.requiredVerification()
                callback()
                this.loading = false
              })
            } else {
              this.reset()
              if (data !== null) {
                // 默认带出流程中必须要传的附件
                this.form.fileList = data.fileList
              }
              // 签约主体带入默认值
              this.bfContractPaymentLoading = true
              findInvestMain(this.dealId).then(response => {
                this.form.bfContractPaymentList = response.data

                this.form.oaSealDetailList = []
                response.data.forEach(item => {
                  var row = {
                    investMain: item.investMain,
                    investMainType: item.investType,
                    spvId: item.spvId
                  }
                  this.$nextTick(() => {
                    this.form.oaSealDetailList.push(row)
                  })
                })
                this.bfContractPlanInvestMainOptions = []
                this.loadingPlanName()
                this.bfContractPaymentLoading = false
              })

              this.form.isPayment = 'no'
              this.form.isSeal = 'N'
            }
          },
          // 加载付款计划主题名称
          loadingPlanName() {
            this.form.bfContractPaymentList.forEach(item => {
              if (item.investMain !== null && item.investMain !== undefined && item.investMain !== '') {
                getLpViewByMainBodyId(item.investMain).then(response => {
                  if (response.data !== null) {
                    var temp = { dictValue: response.data.id, dictLabel: response.data.name }
                    this.bfContractPlanInvestMainOptions.push(temp)
                    this.bfContractPlanInvestMainOptionsTemp.push(temp)
                  }
                })
              }
            })
          },
          // 表单重置
          reset() {
            this.form = {
            id: undefined,
            applyUserId: this.$store.state.user.userId,
            dealId: this.dealId,
            applyTime: new Date(),
            signingTime: undefined,
            name: undefined,
            money: 0,
            type: undefined,
            company: undefined,
            projectOrFund: undefined,
            isPayment: undefined,
            isSeal: undefined,
            useSealOne: undefined,
            useSealTwo: undefined,
            payCompletionTime: undefined,
            abstracts: undefined,
            paymentPrerequisites: undefined,
            specialTerms: undefined,
            createBy: undefined,
            updateBy: undefined,
            createTime: undefined,
            updateTime: undefined,
            fileList: [],
            delFlag: undefined,
            oaSealDetailList: undefined,
            bfContractTermsList: []
            }
            this.resetForm('form')
            this.bfContractPlanInvestMainOptions = []
          },
          // 取消按钮
          cancel() {
            this.$parent.$parent.formOpen = false
            this.reset()
          },
          // 关闭form页面
          closeForm(type) {
            // 关闭form页面遮罩层
            this.loading = false
            // 从流程中保存不需要关闭页面和刷新list
            if (type !== 'actSave') {
              // 关闭form页面
              this.$parent.$parent.formOpen = false
              // 刷新list页面
              this.$parent.$parent.getList()
            }
          },
          submitFormReady(type) {
            const that = this
            try {
              if (this.form.money === 0 || this.form.money === '0') {
                this.form.money = undefined
              }
              that.requiredVerification()
              that.$refs['form'].validate(valid => {
                if (valid) {
                  var temp = that.form.bfContractPaymentList
                  // 如果签约主体中 认缴比例为空时 给个提示
                  if (temp !== null && temp !== undefined && temp !== '') {
                    const result = temp.some(item => {
                      if (item.stake === undefined || item.stake === '' || item.stake === null) {
                        that.$confirm(that.$t('签约主体中有未填写的认缴比例,是否继续?'), that.$t('提示'), {
                          confirmButtonText: that.$t('继续'),
                          cancelButtonText: that.$t('取消'),
                          type: 'warning'
                        }).then(() => {
                          console.log(type)
                          that.submitForm(type)
                        })
                        return true
                      }
                    })
                    if (!result) {
                      that.submitForm(type)
                    }
                  }
                }
              })
            } catch (e) {
              console.log(e)
              that.submitForm(type)
            }
          },
          /** 提交按钮 */
          submitForm(type) {
            return new Promise((resolve, reject) => {
              if ((this.form.isPayment === 'payment' || this.form.isPayment === 'collection')) {
                var flag = false
                var paymentList = []
                var collectionList = []
                if (this.form.isPayment === 'payment') {
                  paymentList = this.form.bfContractPlanList
                }
                if (this.form.isPayment === 'collection') {
                  collectionList = this.form.bfContractPlanList
                }
                if (paymentList !== undefined && paymentList !== null && paymentList !== '' && paymentList.length > 0) {
                  var tempPaymentList = 0
                  paymentList.forEach(item => {
                    tempPaymentList += item.paymentMoney
                  })
                  flag = parseFloat(tempPaymentList) === parseFloat(this.form.money)
                }
                if (collectionList !== undefined && collectionList !== null && collectionList !== '' && collectionList.length > 0) {
                  var tempCollectionMoney = 0
                  collectionList.forEach(item => {
                    tempCollectionMoney += item.collectionMoney
                  })
                  flag = parseFloat(tempCollectionMoney) === parseFloat(this.form.money)
                }
                if (!flag) {
                  this.$confirm(this.$t('收付款计划金额与合同金额不一致,是否继续?'), this.$t('警告'), {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                  }).then(() => {
                    this.submitFormStart(type).then((dataId) => {
                      resolve(dataId)
                    })
                  }).catch(() => {
                    reject()
                  })
                } else {
                  this.submitFormStart(type).then((dataId) => {
                    resolve(dataId)
                  })
                }
              } else {
                this.submitFormStart(type).then((dataId) => {
                  resolve(dataId)
                })
              }
            })
          },
          submitFormStart: function(type) {
            return new Promise((resolve, reject) => {
              this.$refs['form'].validate(valid => {
                var flag = true
                // 用印选择 是 校验
                var seal = this.form.isSeal
                // 收付款类型 校验
                var payment = this.form.isPayment
                var temp = ''
                if (seal === 'Y') {
                  temp = this.form.oaSealDetailList
                  if (temp === null || temp === undefined || temp === '') {
                    this.msgError(this.$t('至少添加一条用印明细!'))
                    flag = false
                  }
                }
                if (payment === 'collection' || payment === 'payment' || payment === 'no') {
                  temp = this.form.bfContractPaymentList
                  if (temp === null || temp === undefined || temp === '' || temp <= 0) {
                    this.msgError(this.$t('至少添加一条签约主体!'))
                    flag = false
                  }
                }
                // 验证数据
                if (valid && flag) {
                  if (type === 'changeContract') {
                    this.startProcess({ id: this.form.id, type: 'changeContract' })
                    resolve()
                  } else {
                    // 弹出遮罩层
                    this.loading = true
                    // 保存方式，如果值为actSave则是从流程表单中进行的保存，默认将delFlag 设置为2,审批通过后在更新为0
                    this.form.saveType = type
                    // 保存数据
                    saveBfContract(this.form).then(response => {
                      if (response.code === 200) {
                        // 点击的按钮是保存并启动流程
                        if (type === 'process') {
                          // 设置数据id方式启动流程后取消并再次启动会创建多条记录
                          // this.form.id = response.data.id
                          this.init({ id: response.data.id })
                          // 启动流程
                          this.startProcess(response.data)
                          // 点击的仅保存
                        } else {
                          this.msgSuccess(this.$t('保存成功'))
                          // 关闭form页面
                          this.closeForm(type)
                        }
                        resolve(response.data.id)
                      } else {
                        this.msgError(response.msg)
                        reject(response)
                      }
                    })
                  }
                } else {
                  reject()
                }
              })
            })
          },
          // 启动流程
          startProcess: async function(data) {
            this.loading = false
            var dealName = await getDealName(this.dealId)
            // 启动流程时候传入的参数
            const processData = {}
            // 待办标题
            processData.title = '「' + dealName + '」' + ':' + this.form.actTitle
            // 业务表名
            processData.dataTable = 'bf_contract'
            // 业务ID
            processData.dataId = data.id
            // 业务表单地址
            processData.formPath = '@/views/bf/contract/bfContractForm'
            processData.viewPath = '@/views/bf/contract/bfContractView'

            // 菜单标识(根据菜单标识判断的走哪个流程)
            processData.menuKey = this.menuKey

            // 是否点击保存按钮后,启动流程前执行方法
            if (data.type === 'changeContract') {
              processData.onBeforeProcess = true
              this.form.oldBfContract = this.oldBfContract
              processData.form = this.form
            }
            this.startProcessByMenu(processData, () => {
              this.form.actStatus = 'D'
              this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
              this.closeForm()
            })
          },
          // 用印明细
          addPayment() {
            const row = {
              id: undefined,
              investMainType: '',
              investMain: '',
              sealType: '',
              remark: ''
            }
            if (!(this.form.oaSealDetailList instanceof Array)) {
              this.$set(this.form, 'oaSealDetailList', [])
            }
            this.$nextTick(() => {
              this.form.oaSealDetailList.push(row)
            })
          },
          // 删除用印明细
          delHandle(index, row) {
            const id = row.id
            if (id !== undefined && id !== '' && id != null) {
              this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
                confirmButtonText: this.$t('确定'),
                cancelButtonText: this.$t('取消'),
                type: 'warning'
              })
                .then(function() {
                  return deleteOaSealDetail(id)
                }).then(() => {
                this.form.oaSealDetailList.splice(index, 1)
                return this.msgSuccess(this.$t('删除成功'))
              })
                .catch(function() {})
            } else {
              this.form.oaSealDetailList.splice(index, 1)
            }
          },
          // 添加收付款计划
          addPaymentPlan() {
            const row = {
              id: undefined,
              name: '',
              type: '',
              currency: 'CNY',
              remark: '',
              remindTime: '',
              remindUserId: ''
            }
            if (!(this.form.bfContractPlanList instanceof Array)) {
              this.$set(this.form, 'bfContractPlanList', [])
            }
            this.$nextTick(() => {
              this.form.bfContractPlanList.push(row)
            })
          },
          // 收付款计划删除
          delHandlePlan(index, row) {
            const id = row.id
            if (id !== undefined && id !== '' && id != null) {
              this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
                confirmButtonText: this.$t('确定'),
                cancelButtonText: this.$t('取消'),
                type: 'warning'
              })
                .then(function() {
                  // ************************
                  // return delO aContractPlan(id)
                }).then(() => {
                this.form.bfContractPlanList.splice(index, 1)
                return this.msgSuccess(this.$t('删除成功'))
              })
                .catch(function() {})
            } else {
              this.form.bfContractPlanList.splice(index, 1)
            }
          },
          // 付款信息
          addPaymentPay() {
            const row = {
              id: undefined,
              name: '',
              type: '',
              remark: '',
              remindTime: '',
              remindUserId: '',
              numberOfShares: undefined,
              investmentAmount: undefined
            }
            if (!(this.form.bfContractPaymentList instanceof Array)) {
              this.$set(this.form, 'bfContractPaymentList', [])
            }
            this.$nextTick(() => {
              this.form.bfContractPaymentList.push(row)
            })
          },
          // 投资协议 + 付款时 计算投资金额总和填写到项目合同
          investmentAmountCompute() {
            if (this.form.bfContractPaymentList) {
              var sumMoney = 0.0
              this.form.bfContractPaymentList.forEach(item => {
                var money = parseFloat(item.investmentAmount)
                if (money === undefined || isNaN(money)) {
                  money = 0.0
                }
                sumMoney += money
              })
              if (sumMoney === 0.0 || sumMoney === 0) {
                this.form.money = undefined
              } else {
                this.form.money = sumMoney
              }
            }
          },
          // 删除付款信息
          delHandlePay(index, row) {
            const id = row.id
            if (id !== undefined && id !== '' && id != null) {
              this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
                confirmButtonText: this.$t('确定'),
                cancelButtonText: this.$t('取消'),
                type: 'warning'
              })
                .then(function() {
                  return delBfContractInvest(id)
                }).then(() => {
                this.changeInvestData()
                this.deleteTempPlanInvestMain(index)
                this.form.bfContractPaymentList.splice(index, 1)
                // 从列表删除后 重新计算合同金额
                this.investmentAmountCompute()
                return this.msgSuccess(this.$t('删除成功'))
              })
                .catch(function() {})
            } else {
              this.changeInvestData()
              this.deleteTempPlanInvestMain(index)
              this.form.bfContractPaymentList.splice(index, 1)
              // 从列表删除后 重新计算合同金额
              this.investmentAmountCompute()
            }
          },
          deleteTempPlanInvestMain(index) {
            // 剔除付款计划的 inveestMian
            var tempDelId = ''
            var tempPlan = this.bfContractPlanInvestMainOptions
            if (tempPlan !== undefined) {
              for (var i = 0; i < tempPlan.length; i++) {
                if (tempPlan[i].dictValue === this.form.bfContractPaymentList[index].investMain) {
                  tempDelId = this.bfContractPlanInvestMainOptions[i].dictValue
                  this.bfContractPlanInvestMainOptions.splice(i, 1)
                }
              }
            }

            if (this.form.bfContractPlanList !== undefined) {
              for (var j = 0; j < this.form.bfContractPlanList.length; j++) {
                if (this.form.bfContractPlanList[j].investId === tempDelId) {
                  this.form.bfContractPlanList.splice(j, 1)
                }
              }
            }
          },
          // 添加关键条款
          addPaymentTerms() {
            const row = {
              id: undefined,
              investType: '',
              investMain: '',
              paymentTime: '',
              paymentMoney: 0,
              collectionTime: '',
              collectionMoney: '',
              currency: '',
              stake: '',
              remark: '',
              status: 1,
              reminderFrequency: 'TIMER',
              cron: '',
              frequencyCronValue: undefined,
              remindUserId: undefined
            }
            if (!(this.form.bfContractTermsList instanceof Array)) {
              this.$set(this.form, 'bfContractTermsList', [])
            }
            this.$nextTick(() => {
              this.form.bfContractTermsList.push(row)
            })
          },
          // 删除关键条款
          delHandleTerms(index, row) {
            var that = this
            console.log('删除条款')
            const id = row.id
            if (id !== undefined && id !== '' && id != null) {
              this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
                confirmButtonText: this.$t('确定'),
                cancelButtonText: this.$t('取消'),
                type: 'warning'
              })
              .then(function() {
                delBfContractTerms(id).then(() => {
                  that.form.bfContractTermsList.splice(index, 1)
                  that.msgSuccess(that.$t('删除成功'))
                })
              }).catch(function() {})
            } else {
              this.form.bfContractTermsList.splice(index, 1)
            }
          },
          // 添加附件
          uploader() {
            this.uploaderOpen = true
            this.title = '上传附件'
          },
          // 删除附件
          delAdjunct(index, file) {
            this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
              confirmButtonText: this.$t('确定'),
              cancelButtonText: this.$t('取消'),
              type: 'warning'
            })
              .then(function() {
                return deleteFileBase(file.id)
              }).then(() => {
              this.form.fileList.splice(index, 1)
              return this.msgSuccess(this.$t('删除成功'))
              })
              .catch(function() {})
          },
          requiredVerification() {
            if (this.form.isPayment !== 'collection') {
              this.bfContractPlanListRules.collectionMoney = [{ required: false, message: this.$t('必填信息'),	trigger: 'blur' }]
              this.bfContractPlanListRules.collectionTime = [{ required: false, message: this.$t('必填信息'),	trigger: 'blur' }]
              this.bfContractPlanListRules.paymentMoney = [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
              this.bfContractPlanListRules.paymentTime = [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
            } else {
              this.bfContractPlanListRules.paymentMoney = [{ required: false, message: this.$t('必填信息'),	trigger: 'blur' }]
              this.bfContractPlanListRules.paymentTime = [{ required: false, message: this.$t('必填信息'),	trigger: 'blur' }]
              this.bfContractPlanListRules.collectionMoney = [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
              this.bfContractPlanListRules.collectionTime = [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
            }
          },
          changeInvestType(index) {
            this.form.bfContractPaymentList[index].investMain = undefined
          },
          changeInvestData(svalue, name) {
            var flagAddPlan = true
            var tempCount = 0
            // 签约主体中是否存在重复
            var tempPay = this.form.bfContractPaymentList
            for (var i = 0; i < tempPay.length; i++) {
              if (tempPay[i].investMain === svalue) {
                tempCount++
                if (tempCount > 1) {
                  this.msgError(this.$t('签约主体存在重复'))
                  const row = {
                    investMainType: tempPay.investType,
                    investMain: ''
                  }
                  if (!(this.form.bfContractPaymentList instanceof Array)) {
                    this.$set(this.form, 'bfContractPaymentList', '')
                  }
                  this.$nextTick(() => {
                    this.form.bfContractPaymentList.push(row)
                  })
                  // 删掉
                  this.form.bfContractPaymentList.splice(i, 1)
                  flagAddPlan = false
                }
              }
            }
            // 收款计划 添加下拉金额单位素
            if (flagAddPlan) {
              if (name !== undefined && svalue !== undefined) {
                var temp = {
                  dictLabel: name,
                  dictValue: svalue
                }
                this.bfContractPlanInvestMainOptionsTemp.push(temp)
              }
            }
            // 整理最终结果
            this.bfContractPlanInvestMainOptions = []
            this.bfContractPlanInvestMainOptionsTemp = this.toRepeatOption(this.bfContractPlanInvestMainOptionsTemp)
            var planOptionsArr = this.bfContractPlanInvestMainOptionsTemp
            tempPay.forEach(item => {
              planOptionsArr.forEach(itemPlan => {
                if (itemPlan.dictValue === item.investMain) {
                  this.bfContractPlanInvestMainOptions.push(itemPlan)
                }
              })
            })
            this.bfContractPlanInvestMainOptions = this.toRepeatOption(this.bfContractPlanInvestMainOptions)
            // 清理付款计划残余ID
            this.cleanUpResidualIdPlan()
          },
          /**
           * 清理付款计划残余ID
           **/
          cleanUpResidualIdPlan() {
            // 获取主体中所有主体的id
            const investIds = []
            if (this.form.bfContractPaymentList !== undefined && this.form.bfContractPaymentList !== null) {
              this.form.bfContractPaymentList.forEach(item => {
                investIds.push(item.investMain)
              })
            }
            // 如果 计划中没有 主体中的Id  就把这个计划清空掉
            if (this.form.bfContractPlanList !== undefined && this.form.bfContractPlanList !== null) {
              this.form.bfContractPlanList.forEach((item) => {
                if (!investIds.includes(item.investId)) {
                  item.investId = undefined
                }
              })
            }
          },
          // 数组去重复
          toRepeatOption(arr) {
            var hash = {}
            return arr.reduce(function(item, next) {
              hash[next.dictValue] ? '' : hash[next.dictValue] = true && item.push(next)
              return item
            }, [])
          },
          changeIsPayment() {
            if (this.form.type === 'TZXY' || this.form.type === 'BCXY') {
              this.form.isPayment = 'payment'
              this.isShowStake = true
            } else {
              this.form.isPayment = 'no'
              this.isShowStake = false
            }
            this.form.money = undefined
            if (this.form.isPayment === 'collection' || this.form.isPayment === 'payment') {
              this.investmentAmountCompute()
            }
          },
          // 合同变更
          async contractChanges(data) {
            console.log('初始化合同变更数据')
            this.loading = true
            // 显示变更按钮
            this.changeContractBtnStatus = true
            this.initForm(data, () => {
              // 显示添加按钮
              // this.form.actStatus = undefined
            })
          },
          // 保存合同变更数据
          onExtraProcessStart(data) {
            return new Promise((resolve, reject) => {
              var form = data.processData.form
              const getCircularReplacer = () => {
                const seen = new WeakSet()
                return (key, value) => {
                  if (typeof value === 'object' && value !== null) {
                    if (seen.has(value)) {
                      return
                    }
                    seen.add(value)
                  }
                  return value
                }
              }
              var forms = JSON.parse(JSON.stringify(form, getCircularReplacer()))
              changeBfContract(forms).then(response => {
                if (response.code === 200 && response.msg !== '变更时发生异常!') {
                  resolve()
                } else {
                  reject()
                }
              })
            })
          },
          // 合同比对按钮
          contractComparisonBtn() {
            this.bfContractProcessOpen = true
            this.title = '合同比对'
            this.$nextTick(() => {
              console.log('债权')
              this.$refs.bfContractProcess.newData = { id: this.form.id, dealId: this.form.dealId }
              this.$refs.bfContractProcess.oldData = { id: this.form.lastHistoricalId, dealId: this.form.dealId }
              this.$refs.bfContractProcess.init()
            })
          },
          remindHandle(index) {
            this.termsIndex = index
            this.remindOpen = true
          },
          remindConfirmHandle() {
            this.$refs['remindForm'].validate(valid => {
              if (valid) {
                this.remindOpen = false
              }
            })
          }
        }
    }
</script>
